package models

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

//测试用例，演示登陆超时，超时后，结束正在运行的队列
//也可以通过http TimeoutHandler(h Handler, dt time.Duration, msg string)  来设置超时

// 在http初始化的时候，设置配置
// s := &http.Server{
// 	Addr:         ":9999",
// 	Handler:      r, //http.TimeoutHandler(r, SHORT, " 超时"),
// 	ReadTimeout:  10 * time.Second,
// 	WriteTimeout: 10 * time.Second,
// }
// s.ListenAndServe()

const SHORT = time.Second * 2

func postLogin(c *gin.Context) {

	ctx, cancel := context.WithTimeout(c.Request.Context(), SHORT)
	defer cancel()
	res := make(chan struct{})

	go excel(ctx, res)

	select {
	case <-ctx.Done():

		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"status": fmt.Sprintf("had time out %d s", SHORT)})
	case <-res:
		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})

	}

}

func excel(ctx context.Context, c chan struct{}) {
	var i = 1

	var fun = func(i int) {
		defer close(c)
		pp(i * 1)
		pp(i * 10)
		pp(i * 1000)
		pp(i * 10000)
		pp(i * 100000)
	}

	select {
	case <-ctx.Done():
		return
	default:
		if i == 1 {
			i++
			fun(i)
		}

	}

}

func pp(i int) {
	log.Printf("%08d-", i)
	time.Sleep(time.Second)
	i++
}
